package jamirr.loader;

import java.util.Optional;
import java.util.ServiceConfigurationError;
import java.util.function.Supplier;

final class ServiceDefinitionImpl<S> implements ServiceDefinition<S> {

    private final String name;
    private final Class<S> loadedClass;

    /**
     * @param name        The name
     * @param loadedClass The loaded class
     */
    public ServiceDefinitionImpl(String name, Class<S> loadedClass) {
        this.name = name;
        this.loadedClass = loadedClass;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public boolean isPresent() {
        return loadedClass != null;
    }

    @Override
    @SuppressWarnings("java:S1181")
    public <X extends Throwable> S orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
        if (loadedClass == null) {
            throw exceptionSupplier.get();
        }
        try {
            return loadedClass.getDeclaredConstructor().newInstance();
        } catch (Throwable e) {
            throw exceptionSupplier.get();
        }
    }

    @Override
    public S load() {
        return Optional.ofNullable(loadedClass).map(aClass -> {
            try {
                return aClass.getDeclaredConstructor().newInstance();
            } catch (Throwable e) {
                throw new ServiceConfigurationError("Error loading service [" + aClass.getName() + "]: " + e.getMessage(), e);
            }
        }).orElseThrow(() -> new ServiceConfigurationError("Call to load() when class '" + name + "' is not present"));
    }
}
